//
//  BaseSpaceVC.swift
//  ZYA
//
//  Created by 邱仙凯 on 2024/12/23.
//  Copyright © 2024 zwb. All rights reserved.
//
 


import UIKit

import SCLAlertView
import JJCollectionViewRoundFlowLayout_Swift
import BiometricAuthentication


class BaseSpaceVC: UIViewController,ModifyPasswordable,noticeAlertable,updateAlertable {
   var newsArr = [NewsList(json: "")]
   var expectMenuList = [String]()
   var expectMenuItemList = [MenuItem]()
   
   var moduleItemArr:[(String,String,String)] = []
   
   
   private var quotesArr = [QuotesModel]()

   
   lazy var collectionView:UICollectionView = {
       // 1.创建layout
       
       let layout = JJCollectionViewRoundFlowLayout_Swift()
       layout.minimumLineSpacing = 1
       layout.minimumInteritemSpacing = 1
//        layout.sectionInset = UIEdgeInsets(top: 18, left: 27, bottom: 16, right: 27)
       
       // 2.创建UICollectionView
       let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height), collectionViewLayout: layout)
       collectionView.backgroundColor = .clear
       collectionView.showsHorizontalScrollIndicator = false
       collectionView.register(GztSpaceCell.self, forCellWithReuseIdentifier: GztSpaceCell.identifier)
       
       collectionView.register(PigFarmQuotesCell.self, forCellWithReuseIdentifier: PigFarmQuotesCell.identifier)
       collectionView.register(PigEditCell.self, forCellWithReuseIdentifier: PigEditCell.identifier)
       
       collectionView.register(FunctionCenterCell.self, forCellWithReuseIdentifier: FunctionCenterCell.identifier)
       collectionView.register(SpaceHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: SpaceHeader.identifier)
       collectionView.register(BlockHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: BlockHeader.identifier)

       return collectionView
   }()
   
  
   var helper = PersonVM()
   var timer4Notice :Timer?
   var notice_start_dt:String?
   var noticeContent:String?
   var notice_start_dtText:UITextField?
   var noticeTitle:String?
   
   lazy var reportAlertArr:[ReportAlertModel] = {
       var m = ReportAlertModel(JSON:["":""])!
       m.msg = defaultMarqueeStr
       m.z_type = "3"
       let v = [m]
       return v
       
   }()
  
   var menuGroupArr = [String]()
   // MARK: -  生命周期
   override func viewWillAppear(_ animated: Bool) {
       super.viewWillAppear(animated)
       BadgeUtil.shared.getBadge({data in
           BadgeUtil.shared.auditNum = data
           self.collectionView.reloadData()
       })
       // 提示修改初始密码
       if UseInitialPassword {
           DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
               KSToast("您还在使用初始密码，请修改")
               DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.2) {
                   self.go2ModifyPassword(force: true) {
                       
                   }
               }
           }
       }
       navigationController?.setNavigationBarHidden(true, animated: false)

   }
   deinit {
       NotificationCenter.default.removeObserver(self)
   }
   
   
   

   override func viewWillDisappear(_ animated: Bool) {
       super.viewWillDisappear(true)

       navigationController?.setNavigationBarHidden(false, animated: false)

   }
   
   var navHHH:CGFloat = 60
   
   var cv = ComDynNavView()
   override func viewDidLoad() {
       super.viewDidLoad()
      
       
 
       menuGroupArr = ["我的常用","功能模块"]
       moduleItemArr = helper.getBigItemArr()
       

       self.title = "工作台"
    
       let bgImg = UIImageView(image: UIImage(named: "common_bg"))
       bgImg.frame = self.view.bounds
       
//        let bgImg = GradientView(frame: CGRect(x: 0, y: 0, width: KSGlobal.screenW, height: 300))
       self.view.addSubview(bgImg)
       
       
       
       cv.frame = CGRect(x:0,y:-navHHH,width:KSGlobal.screenW,height:navHHH)
       cv.titleLab.text = self.title
       cv.searchButton.isHidden = true
//        cv.searchChange = { flag in
//            if !flag {
//                self.keyWord = ""
//                self.searchBar!.text = ""
//                self.dealTempList()
//            }
//        }
//           cv.searchBg.addSubview(searchBar!)
//
//            searchBar!.searchTextField.backgroundColor = UIColor.white
//            searchBar?.backgroundImage = UIImage()
//            searchBar!.placeholder = "搜索"
//            searchBar!.searchTextField.layer.cornerRadius = 19
//            searchBar!.searchTextField.layer.masksToBounds = true
//
//            searchBar!.snp.makeConstraints { make in
//                make.edges.equalToSuperview()
//
//            }
     
       collectionView.addSubview(cv)
     
       
       collectionView.contentInset = UIEdgeInsets(top: navHHH, left: 0, bottom: 10, right: 0)
       
       
       collectionView.delegate = self
       collectionView.dataSource = self
       self.view.addSubview(collectionView)
       
        
       
       self.setMenu()
       
     
       
    
   }
   
   
   // 配置菜单
   func setMenu() {
       expectMenuList = PersistenceUtil.shared.defaultMenu() + ["自定义"]
       let tempMenuItemList = expectMenuList.compactMap { one -> MenuItem? in
           let mArr = MenuPool.filter{ $0.desc.unwrap == one}
           return mArr.first
       }
       let limitIDS = LimitsMenus.compactMap{ $0.menuId }
       expectMenuItemList = tempMenuItemList.filter {  one -> Bool in
           if one.resId == "0" {
               return true
           } else if limitIDS.contains(one.resId.unwrap) {
               return true
           } else {
               return false
           }
       }
       
       self.collectionView.reloadData()
   }
   
   
  
 
 
   

   
}
// MARK: -   代理和数据源
extension BaseSpaceVC:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
   
   
   
   func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
       
       switch menuGroupArr[indexPath.section] {
 
       case "功能模块":
           let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: SpaceHeader.identifier, for: indexPath) as! SpaceHeader
           header.titleLabel.text = menuGroupArr[indexPath.section]
           header.img.image = UIImage(named: "gnmk_he")
           header.jianbianBg.setGradient(type: .left2right, startColor: UIColor(kshex: "f7f9ff"), endColor: .white)
           return header
    
       default:
           let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: BlockHeader.identifier, for: indexPath) as! BlockHeader
           header.titleLabel.text = menuGroupArr[indexPath.section]
           
           return header
           
       }
       
       
      
       
       
   }
   
   func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
       
       return CGSize(width: KSGlobal.screenW, height: 40)
   }
   
   
   func numberOfSections(in collectionView: UICollectionView) -> Int {
       return menuGroupArr.count
   }
   
   func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
       switch menuGroupArr[section] {
 
       case "功能模块":
           return self.moduleItemArr.count
       case "我的常用":
           return self.expectMenuItemList.count

       default:
           return 0
           
       }
      
       
       
   }
   
   func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
       
       switch menuGroupArr[indexPath.section] {
      
       case "功能模块":
           let cell = collectionView.dequeueReusableCell(withReuseIdentifier: GztSpaceCell.identifier, for: indexPath as IndexPath) as! GztSpaceCell
           cell.img.image = UIImage(named:self.moduleItemArr[indexPath.row].0)
           cell.title.text = self.moduleItemArr[indexPath.row].1
           
           return cell
           // 我的常用
       default:
           let cell = collectionView.dequeueReusableCell(withReuseIdentifier: FunctionCenterCell.identifier, for: indexPath as IndexPath) as! FunctionCenterCell
           if self.expectMenuItemList[indexPath.row].title == "自定义" {
               cell.img.image = UIImage(named:"more_item")
           } else {
               if let img = UIImage(named: self.expectMenuItemList[indexPath.row].title.unwrap) {
                   cell.img.image = img
               } else {
                   cell.img.image = UIImage(named:"new_img\(indexPath.row%5 + 1)")
               }
               
           }
           cell.title.text = self.expectMenuItemList[indexPath.row].title.unwrap
           if cell.title.text == "我的公文" {
               cell.badgeNum = BadgeUtil.shared.auditNum.gongwen
           } else {
               cell.badgeNum = nil
           }
           
           return cell
  
           
           
       }
       
   
       
   }
   // 子类实现
   func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
       
       
      
   
       
       
   }
   
   
   // 设置itemsize
   func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
       let sectionW = self.view.ks_width - 24
       
     
       
       switch menuGroupArr[indexPath.section] {
    
       case "功能模块":
           return CGSize(width: sectionW/2 - 25, height: 87)
       case "我的常用":
           if PlatformManager.shared.platform == .zhuYouAn {
               let width = sectionW/3 - 20
               return CGSize(width: width, height: width*0.8)
           } else {
               return CGSize(width: sectionW/4 - 20, height:  sectionW/4 - 10)
           }
       default:
           return CGSize(width: sectionW, height: 40)
  
           
       }
       
       
  
   }
   func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
       switch menuGroupArr[section] {
       case "我的常用":
           return UIEdgeInsets(top: 0, left: 27, bottom: 16, right: 27)
       default:
           return UIEdgeInsets(top: 18, left: 27, bottom: 16, right: 27)
           
       }
   }
   
}
extension BaseSpaceVC : JJCollectionViewDelegateRoundFlowLayout_Swift {
   func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, borderEdgeInsertsForSectionAtIndex section: Int) -> UIEdgeInsets {
       switch menuGroupArr[section] {
       case "我的常用":
           return UIEdgeInsets(top: -6, left: newModuleLeading, bottom: 20, right: newModuleLeading)
       default:
           return UIEdgeInsets.init(top: -6, left: newModuleLeading, bottom: 12, right: newModuleLeading)
       }
   }
   func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, configModelForSectionAtIndex section: Int) -> JJCollectionViewRoundConfigModel_Swift {
       
       switch menuGroupArr[section] {
       
    
       default:
           let model = JJCollectionViewRoundConfigModel_Swift.init()
           model.cornerRadius = 8
           model.backgroundColor = UIColor.white
           return model
  
           
       }
       

       
       
       
   }
}



// MARK: -  版本更新与提示相关
extension BaseSpaceVC {
   
   
   //  新版本内容提示
   func showUpdateNote(versionFromNet:String,content:String) {
       
       let showNewFlag = userDefault.value(forKey: VersionKey.showNewFlag) as? String
       
       if versionFromNet == VERSION {
           if showNewFlag.unwrap.isEmpty {
               self.showle(versionFromNet: versionFromNet, content: content)
           }
           if remoteLargeThanLocal(local: showNewFlag.unwrap, remote: VERSION) {
               self.showle(versionFromNet: versionFromNet, content: content)
           }
       }
       
       
   }
   
   func showle(versionFromNet:String,content:String) {
       if content != "" {
           let descStr = content.replacingOccurrences(of: "#", with: "\n")
           
           let alertC = UIAlertController(title: "\(versionFromNet)版本更新内容", message: descStr, preferredStyle: .alert)
           let waitAct = UIAlertAction(title:"知道了", style:.default, handler: { (_) in
               userDefault.set(VERSION, forKey: VersionKey.showNewFlag)
           } )
           alertC.addAction(waitAct)
           DispatchQueue.main.async {
               self.present(alertC, animated: true, completion: nil)
           }
       }
   }
}



